//引入接口
import {reqCartList,reqDeleteCartListById,reqUpdateCheckedByid} from '@/api'

const state={
    CartList:[]
}
const mutations={
    GETCARTLIST(state,CartList){
        state.CartList = CartList
    }
}
const actions={
     //获取购物车列表数据
     async getCartList({commit}){
        let result = await reqCartList()
        if(result.code == 200){
            commit("GETCARTLIST",result.data)
        }
     },
     //删除购物车产品
     async deleteCartListBySkuId({commit},skuId){
        let result = await reqDeleteCartListById(skuId)
        if(result.code == 200){
           return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
     },
     //修改购物车勾选产品状态
    async UpdateCheckedById({commit},{skuId,isChecked}){
        let result = await reqUpdateCheckedByid(skuId,isChecked)
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
     //删除全部勾选的产品
     deleteCartListCheckedCart({dispatch,getters}){
        //获取购物车中的全部产品
        let PromiseAll = []
        getters.CartList.cartInfoList.forEach(element => {
            //Promise返回的是个Promise对象
            let Promise = element.isChecked==1?dispatch('deleteCartListBySkuId',element.skuId):''
            //将每次返回的Promise对象添加到PromiseAll数组当中
            PromiseAll.push(Promise)
        });
        //把PromiseAll数组当中的Promise对象返回出去，因为组件需要Promise成功或失败状态，好做出相应的操作
        return Promise.all(PromiseAll)
     },
     //全修改全部产品的状态
     UpdateAllCartIsChecked({dispatch,state},isChecked){
        //获取购物车中的全部产品
        let PromiseAll = []
        state.CartList[0].cartInfoList.forEach(element => {
             //Promise返回的是个Promise对象
            let Promise = dispatch('UpdateCheckedById',{skuId:element.skuId,isChecked})
            //将每次返回的Promise对象添加到PromiseAll数组当中
            PromiseAll.push(Promise)
        });
        //把PromiseAll数组当中的Promise对象返回出去，因为组件需要Promise成功或失败状态，好做出相应的操作
        return Promise.all(PromiseAll)
     },
}
const getters={
    CartList(state){
        return state.CartList[0]||{}
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}